<?php

use \Mapper\ComplaintContentModel as ContentMapper;

class ComplaintcontentController extends \Base\AbstractController {

    /**
     * @desc 投诉便捷内容列表
     */
    public function listAction() {
        $paginator = new \Lib\Paginator('complaintContent');
        $paginator->where([]);

        $this->assign('page', $paginator->getPage());
        $this->assign('count', $paginator->count());
        $this->assign('perPage', $paginator->getPerpage());
        $this->assign('lists', $paginator->lists());

    }

    public function editAction() {
        $request = $this->getRequest();
        $id      = (int)$request->get('id');
        $content = (string)trim($request->get('content'));
        $mapper  = ContentMapper::getInstance();
        $model   = $mapper->findById($id);

        if(!$model instanceof \ComplaintContentModel) {
            return false;
        }

        if($request->isPost()) {
            $model->setContent($content);
            $errMsg = $this->validate($model);

            if($errMsg !== false) {
                return \Response::errmsg($errMsg);
            }

            try {
                $rows = $mapper->update($model, ['id' => $id]);

                if($rows > 0) {
                    return \Response::msg();
                } elseif($rows == 0) {
                    return \Response::errmsg('信息未改动!');
                }
            } catch(\Exception $e) {
                return \Response::errmsg($e->getMessage());
            }
        }

        $this->assign('model', $model);
    }

    public function addAction() {
        $request = $this->getRequest();
        $content = (string)trim($request->get('content'));
        $model   = new \ComplaintContentModel();

        if($request->isPost()) {
            $mapper = ContentMapper::getInstance();
            $model->setContent($content);
            $model->setAdd_time(time());

            $errMsg = $this->validate($model);

            if($errMsg !== false) {
                return \Response::errmsg($errMsg);
            }

            try {
                $mapper->insert($model);
                return \Response::msg('添加成功');
            } catch(Exception $exc) {
                return \Response::errmsg($exc->getMessage());
            }
        }

        $this->assign('model', $model);
        $this->display('edit');
        return false;
    }

    /**
     * @desc 删除
     *
     */
    public function delAction() {
        $request = $this->getRequest();
        $id      = $request->get('id');
        $mapper  = ContentMapper::getInstance();

        try {
            $mapper->del(['id' => $id]);
            return \Response::msg('删除成功');
        } catch(\Exception $exc) {
            return \Response::errmsg('系统异常');
        }
    }

    private function validate(\ComplaintContentModel $model) {
        if(empty($model->getContent())) {
            return '内容不能为空';
        }

        return false;
    }

}
